import React, { Component } from 'react';
import Axios from 'axios';

export default class HTTPComponent extends Component {
  state = {
    resData: '',
    fileData: null,
    imgSrc: '',
  }

  handleAction = () => {
    Axios.post('/api', {
      apiName: 'abc',
      someParams: {
        aa: '11',
        bb: 22
      }
    })
      .then(response => {
        console.log(response);
        this.setState({
          resData: JSON.stringify(response.data),
        })
      })
      .catch(error => {
        console.log(error);
      });
  }

  getFileDate = (e) => {
    console.log(e.target.files);
    this.setState({
      fileData: e.target.files[0]
    })
  }

  upload = () => {
    if (!this.state.fileData) return;
    console.log(this.state.fileData);
    let formData = new FormData();
    formData.append('file', this.state.fileData);
    console.log(formData.get('file'))
    Axios.post('/upload', formData, {
      headers:{'Content-Type':'multipart/form-data'}
    })
      .then(response => {
        console.log(response);
        this.setState({
          resData: JSON.stringify(response.data),
          imgSrc: response.data.path,
        })
      })
      .catch(error => {
        console.log(error);
      });
  }

  render() {
    return (
      <div>
        <button onClick={this.handleAction}>发起请求</button>
        <p>
          <input type="file" name="uploadFile" onChange={this.getFileDate} />
          <button onClick={this.upload}>点击上传</button>
        </p>
        <p>响应内容</p>
        <p>{this.state.resData}</p>
        <p>
          <img src={this.state.imgSrc} style={{maxHeight: '300px'}} alt="" />
        </p>
      </div>
    )
  }
}